package com.rain.controller;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.rain.codemother.innderservie.innerUserService;
import com.rain.common.BaseResponse;
import com.rain.common.ResultUtils;
import com.rain.exception.ErrorCode;
import com.rain.exception.ThrowUtils;
import com.rain.dto.chathistory.ChatHistoryQueryRequest;
import com.rain.entity.ChatHistory;
import com.rain.entity.User;
import com.rain.service.ChatHistoryService;
import com.rain.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 *  控制层。
 *
 * @author <a href="https://github.com/liyupi">程序员刘诗雨</a>
 */
@RestController
@RequestMapping("/chatHistory/")
public class ChatHistoryController {

    @Autowired
    private ChatHistoryService chatHistoryService;
    @Resource
    private innerUserService userService;

    /**
     * 分页查询某个应用的对话历史（游标查询）
     *
     * @param appId          应用ID
     * @param pageSize       页面大小
     * @param lastCreateTime 最后一条记录的创建时间
     * @param request        请求
     * @return 对话历史分页
     */
    @GetMapping("app/{appId}")
    public BaseResponse<Page<ChatHistory>> listAppChatHistory(@PathVariable("appId") Long appId,
                                                              HttpServletRequest request,
                                                              @RequestParam(required = false) LocalDateTime  lastCreateTime,
                                                              @RequestParam(defaultValue = "10") int pageSize) {
        User loginUser = innerUserService.getLoginUser(request);
        Page<ChatHistory> chatHistoryPage = chatHistoryService
                .listAppChatHistoryByPage(appId, loginUser, lastCreateTime, pageSize);
        return ResultUtils.success(chatHistoryPage);

    }

    /**
     * 管理员分页查询所有对话历史
     * @param chatHistoryQueryRequest
     * @return
     */
    @PostMapping("admin/app/page")
    public BaseResponse<Page<ChatHistory>> listAllChatHistoryByPageForAdmin(@RequestBody ChatHistoryQueryRequest
                                                                                        chatHistoryQueryRequest) {
        ThrowUtils.throwIf(chatHistoryQueryRequest==null, ErrorCode.PARAMS_ERROR,"参数错误");
        int pageNum = chatHistoryQueryRequest.getPageNum();
        int pageSize = chatHistoryQueryRequest.getPageSize();
        QueryWrapper queryWrapper = chatHistoryService.getQueryWrapper(chatHistoryQueryRequest);
        Page<ChatHistory> chatHistoryPage = chatHistoryService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return ResultUtils.success(chatHistoryPage);

    }

}
